package OrderQueue

import (
	"context"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/service/OrderService"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtimer"
	"time"
)

// 关闭订单定时器，按秒执行
func initCloseNoPayOrderQueue() {
	topicName := "CloseNoPayOrder"
	interval := 1 * 1400 * time.Millisecond
	gtimer.Add(interval, func() {
		msg, isNil, err := queueCli.Pop(topicName)
		if isNil {
			// 无任务
			return
		}
		if err != nil {
			return
		}
		g.Log().Async().Cat("OrderQueue").Info(topicName, " 开始消费 :", msg)
		handleOrderQueue(msg)
	})

	// 按一天执行一次关闭超时未支付的订单，直接查数据库
	gtimer.Add(86400*1400*time.Millisecond, func() {
		closeOneDayOrder()
	})
}
func closeOneDayOrder() {
	ctx := context.Background()
	var oList []*entity.Order
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order").Where(
		"status = 1 AND create_at < ?",
		time.Now().Unix()-86400).Structs(&oList)
	if err != nil {
		g.Log().Async().Cat("closeOneDayOrder").Error("失败：", err)
		return
	}
	if oList == nil {
		g.Log().Async().Cat("closeOneDayOrder").Info("没有需要关闭的订单")
		return
	}
	for _, item := range oList {
		jieguo := OrderService.CloseNoPayOrder(ctx, item.Id)
		g.Log().Async().Cat("closeOneDayOrder").Info("关闭结果：", jieguo)
	}
}
